﻿using CoreShop.App.Units.Helper;
using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Model.FromBody;
using CoreShop.PrintService;
using CoreShop.Services;
using FastMember;
using Loading;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using static CoreShop.Library.GlobalEnumVars;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;

namespace CoreShop.App
{
    public partial class frmSystemSetup : UIForm
    {
        OpaqueCommand cmd = new OpaqueCommand();
        public corecmsprintscheme printscheme = null;
        public corecmsfoodordermaster SelectOrderMaster = null;
        private bool isGetPayments = false;
        public List<corecmspayaccount> payaccounts = new List<corecmspayaccount>();//支付参数
        public frmSystemSetup()
        {
            InitializeComponent();
        }

        private void frmSystemSetup_Load(object sender, EventArgs e)
        {
            tbcMobilePay.TabVisible = false;
            BindComboBoxData();
            GetPrinter();
            BindBillPrint();
            showFullScreen.Checked = AppConstVars.showFullScreen;            
            GetScalePortInfo();
            GetIniPara();
            LoadPaymentList();
        }

        private void GetIniPara()
        {
            try
            {
                nudFCustdispLeft.Text = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "FormLeft")).ToString();
                nudFCustdispTop.Text = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "FormTop")).ToString();
                nudFCustdispHeight.Text = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "FormHeight")).ToString();
                nudFCustdispWidth.Text = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "FormWidth")).ToString();
                int sShowFlag = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "ShowFlag"));
                if (sShowFlag == 1) chbmFCstShow_Flag.Checked = true;
                int sAutoLayout = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "AutoLayout"));
                if (sAutoLayout == 1) chbmFCstShow_Auto.Checked = true;
                int mAdvertiseID = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "AdvertiseID"));
                int sHostFlag = CommFunc.ConvertToInt32(IniFiles.ReadIniData("Local", "HostFlag"));
                if (sHostFlag == 1) chbHostFlag.Checked = true;
                cbo_mFAdvertiseID.SelectedIndex = mAdvertiseID;

                int sHideOrder = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "HideOrder"));
                if (sHideOrder == 1) chbHideOrder.Checked = true;

                cbbOpenCashBox.SelectedValue = CommFunc.ConvertToInt32(IniFiles.ReadIniData("Local", "CashBoxType"));

                //LED顾显
                cboLedType.SelectedIndex = CommFunc.ConvertToInt32(IniFiles.ReadIniData("CustShow", "LedType"));
                cboLedPort.Text = CommFunc.ConvertStrValue(IniFiles.ReadIniData("CustShow", "LedPort"));
                cboBaudRate.Text = CommFunc.ConvertStrValue(IniFiles.ReadIniData("CustShow", "LedBaud"));
            }
            catch { }
        }

        private void GetScalePortInfo()
        {
            try
            {
                txtScalePort.Items.Clear();
                string[] ports = SerialPort.GetPortNames();
                foreach (string port in ports)
                {
                    txtScalePort.Items.Add(port);
                    txtScalePort.Text = ports[0];
                }
                cmbBaudRate.SelectedIndex = 0;
                cmbWeightConvert.SelectedIndex = 0;
                cmbScaleConvert.SelectedIndex = 0;
                cmbScaleType.SelectedIndex = 0;
                txtScalePort.SelectedIndex = 0;
            }
            catch { }
            try
            {
                cmbBaudRate.Text = CommFunc.ConvertToString(IniFiles.ReadIniData("Weight", "BaudRate"));
                cmbWeightConvert.SelectedIndex = CommFunc.ConvertToInt32(IniFiles.ReadIniData("Weight", "Convert"));
                cmbScaleType.SelectedIndex = CommFunc.ConvertToInt32(IniFiles.ReadIniData("Weight", "ScaleType"));
                txtScalePort.Text = CommFunc.ConvertToString(IniFiles.ReadIniData("Weight", "ComPort"));
                cmbReadType.SelectedIndex = CommFunc.ConvertToInt32(IniFiles.ReadIniData("Weight", "ReadType"));
                cmbWeighMode.SelectedIndex = CommFunc.ConvertToInt32(IniFiles.ReadIniData("Weight", "WeighMode"));
            }
            catch { }
        }

        private void FOrders_Shown(object sender, System.EventArgs e)
        {
            try
            {
                if (AppConstVars.systemsetup != null)
                {
                    ControlsDataBinding.DataBind(AppConstVars.systemsetup, this, DataSourceUpdateMode.OnPropertyChanged);
                    this.rowAmountDecimal.SelectedValue = AppConstVars.systemsetup.rowAmountDecimal;
                    this.sumAmountDecimal.SelectedValue = AppConstVars.systemsetup.sumAmountDecimal;
                    this.orderNumberType.SelectedValue = AppConstVars.systemsetup.orderNumberType;
                    this.isMoreSite.Checked = AppConstVars.systemsetup.isMoreSite;
                    this.billNumberFirst.SelectedValue = AppConstVars.systemsetup.billNumberFirst;
                    this.billNumberTime.SelectedValue = AppConstVars.systemsetup.billNumberTime;
                    this.billNumberLast.SelectedValue = AppConstVars.systemsetup.billNumberLast;
                    this.showFoodImg.Checked = AppConstVars.systemsetup.showFoodImg;                    
                    this.mobilePayType.SelectedValue = AppConstVars.systemsetup.mobilePayType;
                    this.refundPayTime.Value = AppConstVars.systemsetup.refundPayTime;
                    this.memberPayTip.SelectedValue = AppConstVars.systemsetup.memberPayTip;
                    this.couponUsage.SelectedValue = AppConstVars.systemsetup.couponUsage;
                    this.printTaskDays.Value = AppConstVars.systemsetup.printTaskDays;
                    this.orderingMode.SelectedValue = AppConstVars.systemsetup.orderingMode;
                    this.isDiscountAll.Checked = AppConstVars.systemsetup.isDiscountAll;
                    this.isKitchen.Checked = AppConstVars.systemsetup.isKitchen;
                    this.isRegionPrint.Checked = AppConstVars.systemsetup.isRegionPrint;
                    this.showKeyboard.Checked = AppConstVars.systemsetup.showKeyboard;
                    this.speechPayInfo.SelectedValue = AppConstVars.systemsetup.speechPayInfo;
                    this.speechRate.Value = AppConstVars.systemsetup.speechRate;
                    this.orderPlaySound.SelectedValue = AppConstVars.systemsetup.orderPlaySound;
                    this.cmbWeighingCodeType.SelectedValue = AppConstVars.systemsetup.weighingCodeType.ObjToInt(0);
                    this.txtWeighingCodeSign.Text = AppConstVars.systemsetup.weighingCodeSign;
                    this.starWeight.Text = AppConstVars.systemsetup.starWeight.ToString();
                    this.cmbAiType.SelectedValue = AppConstVars.systemsetup.aiType;
                    this.mergeOrderItem.Checked = AppConstVars.systemsetup.mergeOrderItem;
                    this.SecondScreemTime.Text = AppConstVars.systemsetup.SecondScreemTime.ToString();
                    this.employeeSelType.SelectedValue = AppConstVars.systemsetup.employeeSelType;
                    this.checkTimes.Text = AppConstVars.systemsetup.checkTimes.ToString();
                    this.locaImgFirst.Checked = AppConstVars.systemsetup.paraPartialModel.locaImgFirst;
                    this.foodImgAutoSave.Checked = AppConstVars.systemsetup.paraPartialModel.foodImgAutoSave;
                    this.aiGoodsCodeType.SelectedValue = AppConstVars.systemsetup.paraPartialModel.aiGoodsCodeType;
                    this.showFoodImgCust.Checked = AppConstVars.systemsetup.showFoodImgCust;
                    this.checkMemberPay.Checked = AppConstVars.systemsetup.paraPartialModel.checkMemberPay;
                    this.mobilePayOnPos.Checked = AppConstVars.systemsetup.paraPartialModel.mobilePayOnPos;
                    this.aiSelGoodsVoice.SelectedValue = AppConstVars.systemsetup.paraPartialModel.aiSelGoodsVoice;
                    this.prinMethod.SelectedValue = AppConstVars.systemsetup.prinMethod;
                    this.autoPrinLable.SelectedValue = AppConstVars.systemsetup.paraPartialModel.autoPrinLable;
                    this.clearAfterPrint.Checked = AppConstVars.systemsetup.paraPartialModel.clearAfterPrint;                    
                    this.foodTypeBindType.SelectedValue = AppConstVars.systemsetup.foodTypeBindType;
                    this.cmbScaleConvert.SelectedIndex = AppConstVars.systemsetup.paraPartialModel.scaleConvert;
                    this.quickPayType.SelectedValue = AppConstVars.systemsetup.paraPartialModel.quickPayType;

                    payaccounts = new corecmspayaccountServices().GetList();
                    if ((payaccounts != null ) && (payaccounts.Count > 0))
                    {
                        var payaccount = payaccounts.Find(p=>p.status == true);
                        if (payaccount != null)
                        {
                            orgId.Text = payaccount.orgId;
                        }
                    }                    
                }
            }
            catch (Exception ex) {
                UIMessageBox.Show(ex.Message, "错误:", UIStyle.Green, UIMessageBoxButtons.OK);
            }
        }

        public void BindComboBoxData()
        {
            try
            {
                #region 加载AI类型
                this.cmbAiType.Items.Clear();
                var aiTypes = EnumHelper.EnumToList<GlobalEnumVars.AiType>();
                cmbAiType.DataSource = aiTypes;
                cmbAiType.DisplayMember = "description";
                cmbAiType.ValueMember = "value";
                if (aiTypes.Count > 0) this.cmbAiType.SelectedValue = (int)GlobalEnumVars.AiType.None;
                #endregion

                #region 加载电子秤条码类型
                this.cmbWeighingCodeType.Items.Clear();
                var weighingCodeTypes = EnumHelper.EnumToList<GlobalEnumVars.WeighingCodeType>();
                cmbWeighingCodeType.DataSource = weighingCodeTypes;
                cmbWeighingCodeType.DisplayMember = "description";
                cmbWeighingCodeType.ValueMember = "value";
                if (weighingCodeTypes.Count > 0) this.cmbWeighingCodeType.SelectedValue = (int)GlobalEnumVars.WeighingCodeType.CodeAmount13;
                #endregion

                #region 加载金额小数
                this.rowAmountDecimal.Items.Clear();
                var printTypeList = EnumHelper.EnumToList<GlobalEnumVars.AmountDecimal>();
                rowAmountDecimal.DataSource = printTypeList;
                rowAmountDecimal.DisplayMember = "description";
                rowAmountDecimal.ValueMember = "value";
                if (printTypeList.Count > 2) this.rowAmountDecimal.SelectedValue = (int)GlobalEnumVars.AmountDecimal.FloorPoint2;

                sumAmountDecimal.DataSource = printTypeList;
                sumAmountDecimal.DisplayMember = "description";
                sumAmountDecimal.ValueMember = "value";
                if (printTypeList.Count > 2) this.sumAmountDecimal.SelectedValue = (int)GlobalEnumVars.AmountDecimal.FloorPoint2;
                #endregion

                #region 加载编牌号
                this.orderNumberType.Items.Clear();
                var orderNumberTypes = EnumHelper.EnumToList<GlobalEnumVars.OrderNumberType>();
                orderNumberType.DataSource = orderNumberTypes;
                orderNumberType.DisplayMember = "description";
                orderNumberType.ValueMember = "value";
                if (orderNumberTypes.Count > 0) this.orderNumberType.SelectedValue = (int)GlobalEnumVars.OrderNumberType.Without;
                #endregion

                #region 加载移动支付
                this.mobilePayType.Items.Clear();
                var mobilePayTypes = EnumHelper.EnumToList<GlobalEnumVars.MobilePayType>();
                mobilePayType.DataSource = mobilePayTypes;
                mobilePayType.DisplayMember = "description";
                mobilePayType.ValueMember = "value";
                if (mobilePayTypes.Count > 0) this.mobilePayType.SelectedValue = (int)GlobalEnumVars.MobilePayType.Nothing;
                #endregion

                #region 加载单号规则
                this.billNumberFirst.Items.Clear();
                var billNoFirsts = EnumHelper.EnumToList<GlobalEnumVars.BillNumberFirst>();
                billNumberFirst.DataSource = billNoFirsts;
                billNumberFirst.DisplayMember = "description";
                billNumberFirst.ValueMember = "value";
                if (billNoFirsts.Count > 0) this.billNumberFirst.SelectedValue = (int)GlobalEnumVars.BillNumberFirst.ByDate ;

                this.billNumberLast.Items.Clear();
                var billNumberLasts = EnumHelper.EnumToList<GlobalEnumVars.BillNumberLast>();
                billNumberLast.DataSource = billNumberLasts;
                billNumberLast.DisplayMember = "description";
                billNumberLast.ValueMember = "value";
                if (billNoFirsts.Count > 0) this.billNumberLast.SelectedValue = (int)GlobalEnumVars.BillNumberLast.ThreeBit;

                this.billNumberTime.Items.Clear();
                var billNoTimes = EnumHelper.EnumToList<GlobalEnumVars.BillNumberTime>();
                billNumberTime.DataSource = billNoTimes;
                billNumberTime.DisplayMember = "description";
                billNumberTime.ValueMember = "value";
                if (billNoTimes.Count > 0) this.billNumberTime.SelectedValue = (int)GlobalEnumVars.BillNumberTime.Settlement;

                #endregion

                #region 加载会员储值支付提示
                this.memberPayTip.Items.Clear();
                var memberPayTips = EnumHelper.EnumToList<GlobalEnumVars.MemberPayTip>();
                memberPayTip.DataSource = memberPayTips;
                memberPayTip.DisplayMember = "description";
                memberPayTip.ValueMember = "value";
                this.memberPayTip.SelectedValue = (int)GlobalEnumVars.MemberPayTip.TurnToCash;
                #endregion

                #region 加载优惠券使用方式
                this.couponUsage.Items.Clear();
                var couponUsages = EnumHelper.EnumToList<GlobalEnumVars.CouponUsage>();
                couponUsage.DataSource = couponUsages;
                couponUsage.DisplayMember = "description";
                couponUsage.ValueMember = "value";
                this.couponUsage.SelectedValue = (int)GlobalEnumVars.CouponUsage.IgnoreNumber;
                #endregion

                #region 加载点餐模式
                this.orderingMode.Items.Clear();
                var orderingModes = EnumHelper.EnumToList<GlobalEnumVars.OrderingMode>();
                orderingMode.DataSource = orderingModes;
                orderingMode.DisplayMember = "description";
                orderingMode.ValueMember = "value";
                this.couponUsage.SelectedValue = (int)GlobalEnumVars.OrderingMode.All;
                #endregion

                #region 加载钱箱打开方式
                this.cbbOpenCashBox.Items.Clear();
                var CashBoxList = EnumHelper.EnumToList<GlobalEnumVars.CashBoxType>();
                cbbOpenCashBox.DataSource = CashBoxList;
                cbbOpenCashBox.DisplayMember = "description";
                cbbOpenCashBox.ValueMember = "value";
                if (CashBoxList.Count > 2) this.cbbOpenCashBox.SelectedValue = (int)GlobalEnumVars.CashBoxType.UnUsed;
                #endregion

                #region 加载移动支付
                this.speechPayInfo.Items.Clear();
                var sSpeechType = EnumHelper.EnumToList<GlobalEnumVars.SpeechType>();
                speechPayInfo.DataSource = sSpeechType;
                speechPayInfo.DisplayMember = "description";
                speechPayInfo.ValueMember = "value";
                if (sSpeechType.Count > 0) this.speechPayInfo.SelectedValue = (int)GlobalEnumVars.SpeechType.UnSpeech;

                this.aiSelGoodsVoice.Items.Clear();
                aiSelGoodsVoice.DataSource = sSpeechType;
                aiSelGoodsVoice.DisplayMember = "description";
                aiSelGoodsVoice.ValueMember = "value";
                if (sSpeechType.Count > 0) this.aiSelGoodsVoice.SelectedValue = (int)GlobalEnumVars.SpeechType.UnSpeech;

                #endregion

                #region 加载移动支付
                this.orderPlaySound.Items.Clear();
                var sOrderPlaySound = EnumHelper.EnumToList<GlobalEnumVars.OrderPlaySound>();
                orderPlaySound.DataSource = sOrderPlaySound;
                orderPlaySound.DisplayMember = "description";
                orderPlaySound.ValueMember = "value";
                if (sOrderPlaySound.Count > 0) this.orderPlaySound.SelectedValue = (int)GlobalEnumVars.OrderPlaySound.UnPlay;
                #endregion

                #region 加载编牌号
                this.employeeSelType.Items.Clear();
                var employeeSelTypes = EnumHelper.EnumToList<GlobalEnumVars.EmployeeSelType>();
                employeeSelType.DataSource = employeeSelTypes;
                employeeSelType.DisplayMember = "description";
                employeeSelType.ValueMember = "value";
                if (employeeSelTypes.Count > 0) this.employeeSelType.SelectedValue = (int)GlobalEnumVars.EmployeeSelType.None;
                #endregion

                #region 加载编牌号
                //this.goodsFontSize.Items.Clear();
                //var goodsFontSizes = EnumHelper.EnumToList<GlobalEnumVars.GoodsFontSize>();
                //goodsFontSize.DataSource = goodsFontSize;
                //goodsFontSize.DisplayMember = "description";
                //goodsFontSize.ValueMember = "value";
                //if (goodsFontSizes.Count > 0) this.goodsFontSize.SelectedValue = (int)GlobalEnumVars.GoodsFontSize.Size11;
                #endregion

                #region 加载编牌号
                this.aiGoodsCodeType.Items.Clear();
                var goodsCodeType = EnumHelper.EnumToList<GlobalEnumVars.AiGoodsCodeType>();
                aiGoodsCodeType.DataSource = goodsCodeType;
                aiGoodsCodeType.DisplayMember = "description";
                aiGoodsCodeType.ValueMember = "value";
                if (goodsCodeType.Count > 0) this.goodsFontSize.SelectedValue = (int)GlobalEnumVars.AiGoodsCodeType.NumberOnly;
                #endregion

                #region 加载电子秤
                this.cmbScaleType.Items.Clear();
                var dScaleType = EnumHelper.EnumToList<GlobalEnumVars.ScaleType>();
                cmbScaleType.DataSource = dScaleType;
                cmbScaleType.DisplayMember = "description";
                cmbScaleType.ValueMember = "value";
                if (dScaleType.Count > 0) this.cmbScaleType.SelectedValue = (int)GlobalEnumVars.AiGoodsCodeType.NumberOnly;
                #endregion

                #region 加载小票打印方式
                this.prinMethod.Items.Clear();
                var dPrinMethod = EnumHelper.EnumToList<GlobalEnumVars.PrinMethod>();
                prinMethod.DataSource = dPrinMethod;
                prinMethod.DisplayMember = "description";
                prinMethod.ValueMember = "value";
                if (dPrinMethod.Count > 0) this.prinMethod.SelectedValue = (int)GlobalEnumVars.PrinMethod.AutoPrin;

                this.autoPrinLable.Items.Clear();
                autoPrinLable.DataSource = dPrinMethod;
                autoPrinLable.DisplayMember = "description";
                autoPrinLable.ValueMember = "value";
                if (dPrinMethod.Count > 0) this.autoPrinLable.SelectedValue = (int)GlobalEnumVars.PrinMethod.SendPrin;
                #endregion

                #region LED顾显
                this.cboLedType.Items.Clear();
                var dLedType = EnumHelper.EnumToList<GlobalEnumVars.LedCustShow>();
                cboLedType.DataSource = dLedType;
                cboLedType.DisplayMember = "description";
                cboLedType.ValueMember = "value";
                if (dLedType.Count > 0) this.cboLedType.SelectedValue = (int)GlobalEnumVars.LedCustShow.None;
                #endregion

                #region 商品分类导航显示
                this.foodTypeBindType.Items.Clear();
                var dfoodTypeBindType = EnumHelper.EnumToList<GlobalEnumVars.FoodTypeBindType>();
                foodTypeBindType.DataSource = dfoodTypeBindType;
                foodTypeBindType.DisplayMember = "description";
                foodTypeBindType.ValueMember = "value";
                if (dfoodTypeBindType.Count > 0) this.foodTypeBindType.SelectedValue = (int)GlobalEnumVars.FoodTypeBindType.ShowFoodType;
                #endregion

                #region 快捷支付方式
                this.quickPayType.Items.Clear();
                var quickPayTypes = EnumHelper.EnumToList<GlobalEnumVars.QuickPayType>();
                quickPayType.DataSource = quickPayTypes;
                quickPayType.DisplayMember = "description";
                quickPayType.ValueMember = "value";
                if (quickPayTypes.Count > 0) this.quickPayType.SelectedValue = (int)GlobalEnumVars.QuickPayType.CastSetBalance;
                #endregion
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 加载打印小票设置
        /// </summary>
        public void BindBillPrint()
        {
            //已选择的票据
            List<corecmsprintschemedetail> details = new corecmsprintschemedetailServices().AsQueryable().Where(p => p.id > 0).ToList();
            List<corecmsprintbilltemplate> templateList = new corecmsprintbilltemplateServices().AsQueryable().Where(p => p.id > 0).ToList();

            BindBillPrintData(details, templateList, this.cmbBillBalance, (int)GlobalEnumVars.PrintbillType.Settlement);
            BindBillPrintData(details, templateList, this.cmbBillClass, (int)GlobalEnumVars.PrintbillType.ClassBill);
            BindBillPrintData(details, templateList, this.cmbBillDeposit, (int)GlobalEnumVars.PrintbillType.UserDeposit);
            BindBillPrintData(details, templateList, this.cmbBillLabel, (int)GlobalEnumVars.PrintbillType.Label);
            BindBillPrintData(details, templateList, this.cmbBillMallOrder, (int)GlobalEnumVars.PrintbillType.MallOrder);
        }

        private void GetPrinter()
        {
            try
            {
                printerName.Items.Clear();
                printerName.Items.Add(GlobalConstVars.defaultPrinter);

                System.Drawing.Printing.PrintDocument print = new System.Drawing.Printing.PrintDocument();
                foreach (string sPrint in System.Drawing.Printing.PrinterSettings.InstalledPrinters)//获取所有打印机名称
                {
                    printerName.Items.Add(sPrint);
                }
                string sDefault = print.PrinterSettings.PrinterName;//默认打印机名
                printerName.Text = print.PrinterSettings.PrinterName;

                var chemeList = new corecmsprintschemeServices().AsQueryable().Where(p => p.id > 0).OrderBy(p => p.id).ToList();
                if (chemeList.Count > 0)
                {
                    printscheme = chemeList.First();
                    printerName.Text = printscheme.printerName;
                    this.gearName.Text = printscheme.gearName;
                    this.address.Text = printscheme.address;
                    this.linkPhone.Text = printscheme.linkPhone;
                    this.region.Text = printscheme.region;
                }
                else {
                    grbBilltemplate.Enabled = false;
                }
            }
            catch
            {
            }
        }


        /// <summary>
        /// 加载打印小票设置
        /// </summary>
        public void BindBillPrintData(List<corecmsprintschemedetail> details, 
            List<corecmsprintbilltemplate> template, UIComboBox uIComboBox,int billtypeId)
        {
            List<EnumEntity> list = new List<EnumEntity>();
            EnumEntity item = new EnumEntity();
            item.description = "无";
            item.value = 0;
            item.title = "无";
            list.Add(item);
            var templateBalance = template.Where(p => p.billtypeId == billtypeId).ToList();
            foreach (var row in templateBalance)
            {
                EnumEntity m = new EnumEntity();
                m.value = row.id;
                m.title = row.name;
                m.description = row.name;
                list.Add(m);
            }
            uIComboBox.DataSource = list;
            uIComboBox.DisplayMember = "description";
            uIComboBox.ValueMember = "value";
            uIComboBox.SelectedValue = item.value;
            var selectItem = details.Where(p => p.billtypeId == billtypeId).FirstOrDefault();
            if (selectItem != null)
            {
                if (selectItem.selectedFlag)
                {
                    uIComboBox.SelectedValue = selectItem.templateId;
                }
            }
        }

        /// <summary>
        /// 加载打印小票设置
        /// </summary>
        public void BindBillPrintSet(UIComboBox uIComboBox)
        {
            var sTemplateId = uIComboBox.SelectedValue.ObjToInt();
            if (sTemplateId == 0)
            {
                ShowInfoTip("没有选择模板,无法操作。");
                return;
            }
            corecmsprintbilltemplate printbilltemplate = new corecmsprintbilltemplateServices().SelectById(sTemplateId);
            if (printbilltemplate == null)
            {
                UIMessageBox.Show("模板不存在，无法修改。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return;
            }
            new ReportServices().SetDesignReport(printbilltemplate);
        }


        private void btnPrint_Click(object sender, EventArgs e)
        {

        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void GetExampleBillNo()
        {
            int index = billNumberFirst.SelectedIndex;
            string firstStr = "";
            switch (index)
            {
                case 2:
                    firstStr = DateTime.Now.ToString("yyMMdd");
                    break;
                case 3:
                    firstStr = DateTime.Now.ToString("yyMM");
                    break;
                case 4:
                    firstStr = DateTime.Now.ToString("yyyyMMdd");
                    break;
                case 5:
                    firstStr = DateTime.Now.ToString("yyyyMM");
                    break;
            }
            index = billNumberLast.SelectedIndex + 3;
            string lastStr = "1";
            string billNo = firstStr + lastStr.PadLeft(index, '0');
            lblExampleBillNo.Text = "生成示例："+ billNo;
        }

        private void cbbBillNoRule_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetExampleBillNo();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (printscheme == null)
                {
                    UIMessageBox.Show("打印机信息不存在，无法保存，请到打印管理添加打印机。", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
                AppConstVars.systemsetup.rowAmountDecimal = this.rowAmountDecimal.SelectedValue.ObjToInt(0);
                AppConstVars.systemsetup.sumAmountDecimal = this.sumAmountDecimal.SelectedValue.ObjToInt(0);
                AppConstVars.systemsetup.orderNumberType = this.orderNumberType.SelectedValue.ObjToInt(0);
                AppConstVars.systemsetup.isMoreSite = this.isMoreSite.Checked;
                AppConstVars.systemsetup.billNumberFirst = this.billNumberFirst.SelectedValue.ObjToInt(0);
                AppConstVars.systemsetup.billNumberLast = this.billNumberLast.SelectedValue.ObjToInt(3);
                AppConstVars.systemsetup.billNumberTime = this.billNumberTime.SelectedValue.ObjToInt(0);
                AppConstVars.systemsetup.showFoodImg = this.showFoodImg.Checked;
                AppConstVars.systemsetup.isDiscountAll = this.isDiscountAll.Checked;
                AppConstVars.systemsetup.mobilePayType = this.mobilePayType.SelectedValue.ObjToInt(0);
                AppConstVars.systemsetup.refundPayTime = this.refundPayTime.Value.ObjToInt(0);
                AppConstVars.systemsetup.memberPayTip = this.memberPayTip.SelectedValue.ObjToInt(3);
                AppConstVars.systemsetup.couponUsage = this.couponUsage.SelectedValue.ObjToInt(0);
                AppConstVars.systemsetup.printTaskDays = this.printTaskDays.Value.ObjToInt(1);
                AppConstVars.systemsetup.orderingMode = this.orderingMode.SelectedValue.ObjToInt(0);
                AppConstVars.systemsetup.isKitchen = this.isKitchen.Checked;
                AppConstVars.systemsetup.showKeyboard = this.showKeyboard.Checked;
                AppConstVars.systemsetup.speechPayInfo = this.speechPayInfo.SelectedValue.ObjToInt(0);
                AppConstVars.systemsetup.orderPlaySound = this.orderPlaySound.SelectedValue.ObjToInt(0);
                AppConstVars.systemsetup.speechRate = this.speechRate.Value.ObjToInt(1);
                AppConstVars.systemsetup.tiktokShopID = this.tiktokShopID.Text;
                AppConstVars.systemsetup.isRegionPrint = this.isRegionPrint.Checked;
                AppConstVars.systemsetup.weighingCodeType = this.cmbWeighingCodeType.SelectedValue.ObjToInt(0);
                AppConstVars.systemsetup.weighingCodeSign = this.txtWeighingCodeSign.Text;
                AppConstVars.systemsetup.starWeight = CommFunc.ConvertToInt32(this.starWeight.Text);
                AppConstVars.systemsetup.aiType = this.cmbAiType.SelectedValue.ObjToInt(0);
                AppConstVars.systemsetup.mergeOrderItem = this.mergeOrderItem.Checked;
                AppConstVars.systemsetup.checkTimes = CommFunc.ConvertToInt32(this.checkTimes.Text);
                int sScreemTime = CommFunc.ConvertToInt32(this.SecondScreemTime.Text);
                if (sScreemTime <= 0) sScreemTime = 3;
                AppConstVars.systemsetup.SecondScreemTime = sScreemTime;
                AppConstVars.systemsetup.employeeSelType = this.employeeSelType.SelectedValue.ObjToInt(0);
                AppConstVars.systemsetup.showFoodImgCust = this.showFoodImgCust.Checked;

                AppConstVars.systemsetup.paraPartialModel.locaImgFirst = this.locaImgFirst.Checked;
                AppConstVars.systemsetup.paraPartialModel.foodImgAutoSave = this.foodImgAutoSave.Checked;
                AppConstVars.systemsetup.paraPartialModel.aiGoodsCodeType = this.aiGoodsCodeType.SelectedValue.ObjToInt(0);
                AppConstVars.systemsetup.paraPartialModel.checkMemberPay = this.checkMemberPay.Checked;
                AppConstVars.systemsetup.paraPartialModel.mobilePayOnPos = this.mobilePayOnPos.Checked;
                AppConstVars.systemsetup.paraPartialModel.aiSelGoodsVoice = this.aiSelGoodsVoice.SelectedValue.ObjToInt(0);                 
                AppConstVars.systemsetup.prinMethod = CommFunc.ConvertToInt32(this.prinMethod.SelectedValue);
                AppConstVars.systemsetup.paraPartialModel.autoPrinLable = CommFunc.ConvertToInt32(this.autoPrinLable.SelectedValue);
                AppConstVars.systemsetup.paraPartialModel.clearAfterPrint = this.clearAfterPrint.Checked;                
                AppConstVars.systemsetup.foodTypeBindType = CommFunc.ConvertToInt32(this.foodTypeBindType.SelectedValue);
                AppConstVars.systemsetup.paraPartialModel.scaleConvert = CommFunc.ConvertToInt32(this.cmbScaleConvert.SelectedIndex);
                AppConstVars.systemsetup.paraPartialModel.quickPayType = CommFunc.ConvertToInt32(this.quickPayType.SelectedValue);

                AppConstVars.systemsetup.paraPartial = JsonConvert.SerializeObject(AppConstVars.systemsetup.paraPartialModel);
                var bl = new corecmssystemsetupService().Update(AppConstVars.systemsetup);
                new corecmspayaccountServices().InsertOrUpdateAsync(payaccounts);
                SaveIniPara();

                printscheme.printerName = printerName.Text;
                printscheme.gearName = this.gearName.Text;
                printscheme.address  = this.address.Text;
                printscheme.linkPhone = this.linkPhone.Text;
                printscheme.region = this.region.Text;
                new corecmsprintschemeServices().UpdateAsync(printscheme);

                List<corecmsprintschemedetail> details = new corecmsprintschemedetailServices().AsQueryable().Where(p => p.id > 0).ToList();
                SaveBillPrint(details, this.cmbBillBalance, (int)GlobalEnumVars.PrintbillType.Settlement);
                SaveBillPrint(details, this.cmbBillClass, (int)GlobalEnumVars.PrintbillType.ClassBill);
                SaveBillPrint(details, this.cmbBillDeposit, (int)GlobalEnumVars.PrintbillType.UserDeposit);
                //SaveBillPrint(details, this.cmbBillLabel, (int)GlobalEnumVars.PrintbillType.Label);
                SaveBillPrint(details, this.cmbBillMallOrder, (int)GlobalEnumVars.PrintbillType.MallOrder);
                SaveBillPrint(details, this.cmbBillBalance, (int)GlobalEnumVars.PrintbillType.Settlement);
                new corecmsprintschemedetailServices().InsertOrUpdateAsync(details);

                if (bl) UIMessageBox.Show("保存成功。", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "错误:", UIStyle.Green, UIMessageBoxButtons.OK);
            }
        }

        private void SaveIniPara()
        {
            AppConstVars.showFullScreen = showFullScreen.Checked;
            int sCheckedValue = showFullScreen.Checked ? 1:0;
            IniFiles.IniWriteValue("Local", "ShowFullScreen", sCheckedValue.ToString());
            IniFiles.IniWriteValue("CustShow", "FormLeft", nudFCustdispLeft.ToString());
            IniFiles.IniWriteValue("CustShow", "FormTop", nudFCustdispTop.ToString());
            IniFiles.IniWriteValue("CustShow", "FormHeight", nudFCustdispHeight.ToString());
            IniFiles.IniWriteValue("CustShow", "FormWidth", nudFCustdispWidth.ToString());
            sCheckedValue = chbmFCstShow_Flag.Checked ? 1 : 0;
            IniFiles.IniWriteValue("CustShow", "ShowFlag", sCheckedValue.ToString());
            sCheckedValue = chbmFCstShow_Auto.Checked ? 1 : 0;
            IniFiles.IniWriteValue("CustShow", "AutoLayout", sCheckedValue.ToString());
            IniFiles.IniWriteValue("CustShow", "AdvertiseID", cbo_mFAdvertiseID.SelectedIndex.ToString());
            sCheckedValue = chbHideOrder.Checked ? 1 : 0;
            IniFiles.IniWriteValue("CustShow", "HideOrder", sCheckedValue.ToString());

            //LED顾显
            IniFiles.IniWriteValue("CustShow", "LedType", cboLedType.SelectedIndex.ToString());
            IniFiles.IniWriteValue("CustShow", "LedPort", cboLedPort.Text.ToString());
            IniFiles.IniWriteValue("CustShow", "LedBaud", cboBaudRate.Text.ToString());

            sCheckedValue = chbHostFlag.Checked ? 1 : 0;
            IniFiles.IniWriteValue("Local", "HostFlag", sCheckedValue.ToString());
            IniFiles.IniWriteValue("Local", "CashBoxType", cbbOpenCashBox.SelectedValue.ToString());

            //称重设置
            IniFiles.IniWriteValue("Weight", "BaudRate", CommFunc.ConvertToInt32(cmbBaudRate.Text).ToString());
            IniFiles.IniWriteValue("Weight", "Convert", cmbWeightConvert.SelectedIndex.ToString());
            IniFiles.IniWriteValue("Weight", "ScaleType", cmbScaleType.SelectedIndex.ToString());
            IniFiles.IniWriteValue("Weight", "ComPort", txtScalePort.Text.ToString()); 
            IniFiles.IniWriteValue("Weight", "ReadType", cmbReadType.SelectedIndex.ToString());
            IniFiles.IniWriteValue("Weight", "WeighMode", cmbWeighMode.SelectedIndex.ToString());

            ProcessUtil.GetIniParaSetup();
        }

        /// <summary>
        /// 加载打印小票设置
        /// </summary>
        public void SaveBillPrint(List<corecmsprintschemedetail> details,UIComboBox uIComboBox, int billtypeId)
        {
            int templateId = uIComboBox.SelectedValue.ObjToInt();
            var chemedetail = details.Where(p => p.printSchemeId == printscheme.id && p.billtypeId == billtypeId).FirstOrDefault();
            if (chemedetail != null) 
            {
                chemedetail.selectedFlag = true;
                chemedetail.templateId = templateId;
                if (templateId == 0) chemedetail.selectedFlag = false;
                //if (billtypeId == (int)GlobalEnumVars.PrintbillType.Label)
                //{
                //    var chemeData = new corecmsprintbilltemplateServices().GetById(templateId);
                //    if (chemeData != null)
                //    {
                //        chemeData.foodPrintType = CommFunc.ConvertToInt32(foodPrintType.SelectedValue);
                //        new corecmsprintbilltemplateServices().UpdateAsync(chemeData);
                //    }
                //}                    
            }
        }

        private void cbbMobilePayType_SelectedValueChanged(object sender, EventArgs e)
        {
            tbcMobilePay.SelectedIndex = CommFunc.ConvertToInt32(mobilePayType.SelectedValue);
        }

        private void btnCleareData_Click(object sender, EventArgs e)
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isClearData, 0)) return;
            var frm = new frmDataClear();
            frm.ShowDialog();
            frm.Dispose();
        }

        private string GetItemName(int index)
        {
            return "btnPayment" + index.ToString();
        }

        private void LoadPaymentList()
        {
            var payList = new corecmspaymentsService().AsQueryable()
                .Where(p=>p.storeId == AppConstVars.sysUser.storeId).ToList();           
            ProcessUtil.GetSystemPayment();//打开支付方式表
            if ((payList == null) || (payList.Count == 0)) return;
            int index = 1;
            foreach (var pay in payList)
            {
                var mControl = this.Controls.Find(GetItemName(index),true);
                if ((mControl.Length > 0) && (mControl[0] != null))
                {
                    var item = (UIImageButton)mControl[0];
                    if (item != null)
                    {
                        item.Tag = pay.id.ToString();
                        item.Text = pay.name;
                        if (!pay.isEnable) item.Text = "*"+ pay.name + "*";
                        item.Visible = true;
                    }
                }
                index++;
            }
            var mControl1 = this.Controls.Find(GetItemName(index), true);
            if ((mControl1.Length > 0) && (mControl1[0] != null))
            {
                var item1 = (UIImageButton)mControl1[0];
                if (item1 != null)
                {
                    item1.Visible = true;
                }
            }            
        }

        private bool GetPaymentRmo()
        {
            if (isGetPayments) return false;//只同步一次足以
            //string msg = "";
            //var locaPayList = new corecmspaymentsService().GetList();
            //List<corecmspayments> payments = new PosRemoteServices(AppConstVars.sUrl).GetPaymentList(AppConstVars.sysUser.ccessToken, ref msg);
            //if ((payments != null) && (payments.Count > 0) && (payments.Count > locaPayList.Count))
            //{
            //    if (new corecmspaymentsService().InsertOrUpdate(payments))
            //    {
            //        LoadPaymentList();
            //        UIMessageBox.Show("已成功同步云端付款方式到本地，要增加新的付款方式，请重新增加。", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
            //        isGetPayments = true;
            //        return true;
            //    }
            //}
            return false;
        }

        private void btnScaleList_Click(object sender, EventArgs e)
        {
            frmScaleList frm = new frmScaleList();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void btnAiSetup_Click(object sender, EventArgs e)
        {
            if (cmbAiType.SelectedIndex == (int)GlobalEnumVars.AiType.Czl)
            {
                frmSetupCzlAi fi = new frmSetupCzlAi();
                fi.Owner = this;
                fi.ShowDialog();
                fi.Dispose();
            } 
            else
            if (cmbAiType.SelectedIndex == (int)GlobalEnumVars.AiType.Lxx)
            {
                frmSetupLxxAi fi = new frmSetupLxxAi();
                fi.Owner = this;
                fi.ShowDialog();
                fi.Dispose();
            }
        }

        private async void btnGetPayFromRmo_Click(object sender, EventArgs e)
        {
            try
            {
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                ReturnModel result = await SystemApiUtil.GetPayAccountList(AppConstVars.sysUser);
                if (result.Status != ReturnStatus.Success)
                {                
                    UIMessageBox.Show("加载后台数据失败。", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }

                PayAccounModelReturnModel returnModel = result.MessageOrString.JsonToEntity<PayAccounModelReturnModel>();
                if (returnModel == null || returnModel.code != 200)
                {
                    UIMessageBox.Show("加载后台数据失败。", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
                if (returnModel.rows == null || returnModel.rows.Count <= 0)
                {
                    UIMessageBox.Show("没有可使用的支付配置数据。", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
                var payAccounModel = returnModel.rows.Find(p => p.status == 1 && p.accountType == 1);
                if (payAccounModel == null)
                {
                    UIMessageBox.Show("没有找到可使用的支付配置数据。", "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
                //orgId.Text = payAccounModel.orgId;
                sxfMno.Text = payAccounModel.appId;
                //if (string.IsNullOrEmpty(orgId.Text))
                //{
                //    orgId.ReadOnly = false;
                //    orgId.Enabled = true;
                //}
                /*
                TenantModel tenantModel = await CommApiUtil.GetTenantInfo();
                if (tenantModel == null)
                {
                    UIMessageBox.Show("获取商户资料失败。", "错误:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
                SysAgenModel agenModel = await CommApiUtil.GetSysAgentInfo(tenantModel.agentId);
                if (agenModel == null)
                {
                    UIMessageBox.Show("获取服务商资料失败。", "错误:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
                if (agenModel.orgId.IsNullOrEmpty())
                {
                    UIMessageBox.Show("组织机构ID未填写。", "错误:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }                

                var payaccount = payaccounts.Find(p => p.orgId == agenModel.orgId);
                if (payaccount == null)
                {
                    var payaccountNew = new corecmspayaccount();
                    payaccountNew.orgId = agenModel.orgId;
                    payaccountNew.status = true;
                    payaccountNew.orgName = agenModel.AgentName;
                    payaccountNew.sign = new SxfPay(AppConstVars.systemsetup, AppConstVars.payaccount).privateKeyPem;
                    payaccounts.Add(payaccountNew);
                }

                foreach (var account in payaccounts)
                {
                    account.status = false;
                    if (account.orgId.Equals(agenModel.orgId))
                    {
                        account.status = true;
                        orgId.Text = agenModel.orgId;
                        sxfMno.Text = payAccounModel.appId;
                    }
                }
                */
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "错误:", UIStyle.Green, UIMessageBoxButtons.OK);
            }
            finally { cmd.HideOpaqueLayer(); }
        }

        private void btnBillBalance_Click(object sender, EventArgs e)
        {            
            BindBillPrintSet(this.cmbBillBalance);        
        }

        private void btnBillClass_Click(object sender, EventArgs e)
        {
            BindBillPrintSet(this.cmbBillClass);  
        }

        private void btnBillDeposit_Click(object sender, EventArgs e)
        {
            BindBillPrintSet(this.cmbBillDeposit); 
        }

        private void btnBillLabel_Click(object sender, EventArgs e)
        {
            BindBillPrintSet(this.cmbBillLabel);
        }

        private void btnBillMallOrder_Click(object sender, EventArgs e)
        {
            BindBillPrintSet(this.cmbBillMallOrder);
        }

        private void btnPrinterSet_Click(object sender, EventArgs e)
        {
            if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isSysSetup, 0)) return;
            var frm = new frmPrintScheme();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void btnPayAccountSet_Click(object sender, EventArgs e)
        {
            frmPayAccountList frm = new frmPayAccountList();
            frm.Owner = this;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                btnGetPayFromRmo_Click(null, null);
            }
            frm.Dispose();
        }

        private void GetReportFile(int billtypeId)
        {
            string sFileName = "";
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Title = "选择一个Grf文件";
            openFileDialog1.Multiselect = true;
            openFileDialog1.Filter = "GridReport文件|*.grf";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                foreach (string fileName in openFileDialog1.FileNames)
                {
                    sFileName = fileName;
                }
            }

            if (string.IsNullOrEmpty(sFileName)) return;
            if (!(new GridReportHelper().ImportRptByFile(this, sFileName, billtypeId))) 
                return;
            BindBillPrint();
            UIMessageBox.Show("导入成功。");
        }

        private void btnBillBalanceIpt_Click(object sender, EventArgs e)
        {
            var billtypeId = CommFunc.ConvertToInt32((sender as UIButton).Tag);
            GetReportFile(billtypeId);
        }

        private void lblMessage_Click(object sender, EventArgs e)
        {
            UIMessageDialog.ShowMessageDialog("【一商品一单】和【一数量一单】的打印需在商品管理设置商品对应的打印机。", UILocalize.InfoTitle, false, Style);
        }

        private void btnPaymentSet_Click(object sender, EventArgs e)
        {
            var frm = new frmPaymentSet();
            frm.ShowDialog();
            frm.Dispose();
        }
    }
}
